<!--
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-15 15:33:47
-->
<template>
  <div class="container">
    <el-card>
      <!-- 添加按钮 -->
      <template #header>
        <el-button type="primary" :icon="Plus" @click="addTrademark">添加</el-button>
      </template>

      <!-- 表格 -->
      <el-table :data="state.trademarkList" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="tmName" label="品牌名称" />
        <el-table-column prop="logoUrl" label="品牌LOGO">
          <template #default="{ row }">
            <img class="logo" :src="row.logoUrl" alt="" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="small" type="warning" :icon="Edit" @click="updateTrademark(row.id)"
              >修改</el-button
            >
            <el-button size="small" type="danger" :icon="Delete" @click="delTrademark(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="state.page"
        v-model:page-size="state.limit"
        :page-sizes="[10, 15, 20, 25]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <!-- 弹框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isAddOrUpdate ? '添加品牌' : '编辑品牌'"
        width="50%"
        align-center
        :before-close="handleClose"
        @close="closeDialog(ruleFormRef)"
      >
        <!-- 表单 -->
        <el-form
          ref="ruleFormRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="品牌名称" prop="tmName">
            <el-input v-model="formData.tmName" />
          </el-form-item>

          <!-- 图片上传 -->
          <el-form-item label="品牌Logo" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              action="/api/admin/product/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="formData.logoUrl" :src="formData.logoUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>

        <!-- 弹框的取消和确定按钮 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="dialogOk()"> 确定 </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import {
  reqAddBaseTrademarkRes,
  reqBaseTrademarkDetail,
  reqTrademarkRes,
  reqUpdateBaseTrademark
} from '@/api/product'
import type { reqBaseTrademarkDetailRes, trademarkState } from '@/types/trademark'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type UploadProps
} from 'element-plus'
import { reqRemoveRes } from '@/api/product'

// 图片上传成功时
const handleAvatarSuccess: UploadProps['onSuccess'] = async (response, uploadFile) => {
  formData.value.logoUrl = response.data
  ruleFormRef.value?.validateField('logoUrl')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/gif') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 15) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 表单引用
const ruleFormRef = ref<FormInstance>()

// 控制弹框显示
const dialogVisible = ref(false)

// 新增和编辑功能需要收集的数据
const formData = ref({
  tmName: '',
  logoUrl: ''
})

// 控制弹框的标题
const isAddOrUpdate = ref(true)

// 新增和编辑弹框关闭之前
const handleClose = () => {
  dialogVisible.value = false
}
// 弹框关闭时的回调 清空弹框数据
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 点击弹框确定按钮
const dialogOk = async () => {
  await ruleFormRef.value?.validate()

  const res = isAddOrUpdate.value
    ? await reqAddBaseTrademarkRes(formData.value)
    : await reqUpdateBaseTrademark(formData.value)

  if (res.code === 200) {
    ElMessage.success(isAddOrUpdate.value ? '添加成功' : '修改成功')
    getTrademarkData()
    dialogVisible.value = false
  }
}

// 添加按钮
const addTrademark = () => {
  isAddOrUpdate.value = true
  dialogVisible.value = true
}

// 编辑按钮
const updateTrademark = async (id: number) => {
  isAddOrUpdate.value = false
  dialogVisible.value = true
  const res = await reqBaseTrademarkDetail(id)
  if (res.code === 200) {
    formData.value = res.data
  }
}

// 删除按钮
const delTrademark = (row: reqBaseTrademarkDetailRes) => {
  ElMessageBox.confirm(`确定要删除${row.tmName}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await reqRemoveRes(row.id)
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
      }
      getTrademarkData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 表单验证
const rules = reactive({
  tmName: [{ required: true, message: '不能为空', trigger: 'blur' }],
  logoUrl: [{ required: true, message: '请上传图片', trigger: 'change' }]
})

// #region 品牌列表和分页逻辑

// 获取品牌数据
const state: trademarkState = reactive({
  page: 1,
  limit: 10,
  total: 0,
  trademarkList: []
})
// 分页改变时
const handleSizeChange = (val: number) => {
  state.limit = val
  getTrademarkData()
}

const handleCurrentChange = (val: number) => {
  state.page = val
  getTrademarkData()
}

// 获取品牌管理数据
const getTrademarkData = async () => {
  const res = await reqTrademarkRes(state.page, state.limit)
  if (res.code === 200) {
    state.total = res.data.total
    state.trademarkList = res.data.records
  }
}
// 获取品牌管理数据
onMounted(() => {
  getTrademarkData()
})

//#endregion
</script>

<script lang="ts">
export default {
  name: 'TradeMark'
}
</script>

<style lang="scss" scoped>
.container {
  margin-top: 20px;
}
.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.logo {
  width: 100px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
